package com.crm.system.service.impl.opportunityManager;

import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.cluePoolManager.ClueFollow;
import com.crm.model.entity.cluePoolManager.ClueVisitRecord;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerContactPerson;
import com.crm.model.entity.opportunityManager.Opportunity;
import com.crm.model.entity.opportunityManager.OpportunityCollaborator;
import com.crm.model.entity.opportunityManager.OpportunityContact;
import com.crm.model.entity.opportunityManager.OpportunityDynamic;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.cluePoolManager.ClueFollowQO;
import com.crm.model.vo.customerManager.CustomerContactVO;
import com.crm.model.vo.opportunityManager.OpportunityCollaboratorVO;
import com.crm.model.vo.opportunityManager.OpportunityDynamicVO;
import com.crm.model.vo.opportunityManager.OpportunityVO;
import com.crm.service.cluePoolManager.ClueFollowDbService;
import com.crm.service.cluePoolManager.ClueVisitRecordDbService;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.service.customerManager.CustomerPoolDbService;
import com.crm.service.opportunityManager.OpportunityCollaboratorDbService;
import com.crm.service.opportunityManager.OpportunityDbService;
import com.crm.service.opportunityManager.OpportunityDynamicDbService;
import com.crm.system.service.cluePoolManager.ClueContactService;
import com.crm.system.service.cluePoolManager.ClueFollowService;
import com.crm.system.service.contactManager.ContactInformationService;
import com.crm.system.service.opportunityManager.OpportunityCollaboratorService;
import com.crm.system.service.opportunityManager.OpportunityContactService;
import com.crm.system.service.opportunityManager.OpportunityDynamicService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * bj
 * 商机动态
 */
@Service
public class OpportunityDynamicServiceImpl implements OpportunityDynamicService {

    @Autowired
    private OpportunityDynamicDbService opportunityDynamicDbService;

    @Autowired
    private ClueFollowDbService clueFollowDbService;

    @Autowired
    private OpportunityDbService opportunityDbService;

    @Autowired
    private ContactDbService contactDbService;

    @Autowired
    private OpportunityContactService opportunityContactService;

    @Autowired
    private CustomerDbService customerDbService;

    @Autowired
    private ClueVisitRecordDbService clueVisitRecordDbService;

    /**
     * 商机管理-新增商机动态
     * @param clueFollowQO 商机动态和跟进记录信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public List<OpportunityDynamicVO> addOpportunityDynamic(ClueFollowQO clueFollowQO) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        Boolean result = false;
        String contactId = clueFollowQO.getContactId();

        //0跟进  1修改商机状态
        if(0 == clueFollowQO.getOperationMode()){

            //查询是手输的联系人,向商机联系人添加
            Contact contact = contactDbService.getContactId(clueFollowQO.getCustomerId(), clueFollowQO.getContactInformation(), clueFollowQO.getContactName());
            if(StringUtils.isBlank(contact.getContactId())){ //没值

                //向商机联系人添加数据
                OpportunityContact opportunityContact = new OpportunityContact();
                opportunityContact.setContactName(clueFollowQO.getContactName());
                opportunityContact.setContactPosition("3");
                opportunityContact.setContactInformation(clueFollowQO.getContactInformation());
                opportunityContact.setContactType(1);  //次要联系人
                opportunityContact.setOpportunityId(clueFollowQO.getOpportunityId());
                opportunityContactService.addOpportunityContact(opportunityContact);

                //向联系人添加数据
                /*Contact con = new Contact();
                contactId = CommonUtils.getGUID();
                con.setContactId(contactId);
                con.setContactName(clueFollowQO.getContactName());
                con.setContactPosition("3");
                con.setContactInformation(clueFollowQO.getContactInformation());
                con.setOnTheJobSituation(0); //在职情况 --- 0: 在职; 1: 离职
                contact.setFollowUpTimes(0);
                con.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                con.setMemberGrade(1);//客户类型   会员客户-1  非会员客户-2
                con.setAbolishState(1); // 废止状态  1启动 2废止
                con.setCustomerId(clueFollowQO.getCustomerId());
                con.setAccountId(userAccount.getAccountId());
                con.setCompanyId(userAccount.getCompanyId());
                con.setCreatePeopleId(userAccount.getAccountId());
                con.setCreateTm(new Date());
                con.setUpdatePeopleId(userAccount.getAccountId());
                con.setUpdateTm(new Date());
                result = contactDbService.addContact(con);

                //向联系方式表里插入数据
                ContactInformation contactInformation = new ContactInformation();
                String contactInformationId = CommonUtils.getGUID();
                contactInformation.setContactInformationId(contactInformationId);
                contactInformation.setContactInformation(clueFollowQO.getContactInformation());
                contactInformation.setContactType("商家添加的电话");
                //联系方式类型  0主联系方式 1从联系方式
                contactInformation.setContactInformationType(0);
                contactInformation.setContactId(contactId);
                contactInformation.setCustomerId(clueFollowQO.getCustomerId());
                contactInformation.setCreatePeopleId(userAccount.getAccountId());
                contactInformation.setCreateTm(new Date());
                contactInformation.setUpdatePeopleId(userAccount.getAccountId());
                contactInformation.setUpdateTm(new Date());
                contactInformation.setAbolishState(1);  //废止状态  1启动 2废止
                contactInformation.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                contactInformation.setContactId(contactId);
                contactInformationService.addContactInformation(contactInformation);



                //向客户联系人里面添加数据
                CustomerContactPerson customerContactPerson = new CustomerContactPerson();
                String customerContactPersonId = CommonUtils.getGUID();
                customerContactPerson.setCustomerContactPersonId(customerContactPersonId);
                customerContactPerson.setContactName(clueFollowQO.getContactName());
                customerContactPerson.setContactPosition("3");
                customerContactPerson.setContactInformation(clueFollowQO.getContactInformation());
                customerContactPerson.setOnTheJobSituation(0);
                customerContactPerson.setIsSeniorExecutive(1);
                customerContactPerson.setFollowUpTimes(0);
                customerContactPerson.setAbolishState(1); // 废止状态  1启动 2废止
                customerContactPerson.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
                customerContactPerson.setContactState(2); //联系人类型    主联系人-1   从联系人-2
                customerContactPerson.setMergeState(0);
                customerContactPerson.setCustomerId(clueFollowQO.getCustomerId());
                customerContactPerson.setCreatePeopleId(userAccount.getAccountId());
                customerContactPerson.setCreateTm(new Date());
                customerContactPerson.setUpdatePeopleId(userAccount.getAccountId());
                customerContactPerson.setUpdateTm(new Date());
                customerPoolDbService.addCustomerContactPerson(customerContactPerson);*/

            }

            //添加跟进记录
            ClueFollow clueFollow = new ClueFollow();
            String clueFollowId = CommonUtils.getGUID();
            clueFollow.setClueFollowId(clueFollowId);
            clueFollow.setFollowWay(clueFollowQO.getFollowWay());
            clueFollow.setFollowTm(new Date());
            clueFollow.setFollowDetail(clueFollowQO.getFollowDetail());
            clueFollow.setFollowPurpose("3"); //跟进目的：1-产品跟进；2-过程跟进; 3-商机跟进
            clueFollow.setCustomerIntention(clueFollowQO.getCustomerIntention()); //客户意向(百分比)
            clueFollow.setOpportunityStatus(clueFollowQO.getOpportunityStatus()); //商机状态 1: 初步洽谈 2: 需求确定 3: 方案报价 4: 谈判 5: 洽谈合同 6: 赢单 7: 输单
            clueFollow.setFollowSource(5);
            clueFollow.setCustomerId(clueFollowQO.getCustomerId());
            clueFollow.setContactId(contactId);
            clueFollow.setCreatePeopleId(userAccount.getAccountId());
            clueFollow.setCreateTm(new Date());
            clueFollow.setUpdatePeopleId(userAccount.getAccountId());
            clueFollow.setUpdateTm(new Date());


            //类别为拜访 陪访 添加拜访表里数据
            if(clueFollowQO.getFollowWay()==2 ||clueFollowQO.getFollowWay()==6) {//2-拜访 6-陪访
                //新增拜访记录
                String clueVisitVecordid = insertClueVisitVecord(clueFollowQO, userAccount);
                clueFollow.setVisitRecordId(clueVisitVecordid);//线索拜访表id
            }

            result = clueFollowDbService.addClueFollow(clueFollow);

            //成交意向大于0就是意向客户,修改客户状态
            int customerIntention = Integer.parseInt(clueFollowQO.getCustomerIntention());
            if(customerIntention > 0) {
                //获取当前用户
                Customer customer = new Customer();
                customer.setCustomerId(clueFollowQO.getCustomerId());
                customer.setPotentialCustomers(customerIntention);
                customer.setUpdatePeopleId(userAccount.getAccountId());
                customer.setUpdateTm(new Date());
                customerDbService.updateCustomerById(customer);
            }

        }

        //List<OpportunityDynamic> list =new ArrayList<>();
//        if(1 == clueFollowQO.getOperationMode()){
//            list = opportunityDynamicDbService.selectByOpportunityId(clueFollowQO.getOpportunityId(),1);
//        }

        /*if(list.size() !=0) {
            OpportunityDynamic opp = list.get(0);
            opp.setOpportunityStatus(clueFollowQO.getOpportunityStatus());
            //修改商机动态
            result = opportunityDynamicDbService.updateOpportunityDynamic(opp);*/
        //}else{
            OpportunityDynamic opportunityDynamic = new OpportunityDynamic();
            String opportunityDynamicId = CommonUtils.getGUID();
            opportunityDynamic.setOpportunityDynamicId(opportunityDynamicId);
            opportunityDynamic.setAccountId(userAccount.getAccountId());
            opportunityDynamic.setUserName(userAccount.getUserName());
            //0跟进  1修改商机状态
            if(0 == clueFollowQO.getOperationMode()){
                opportunityDynamic.setFollowTm(clueFollowQO.getFollowTm());
                opportunityDynamic.setFollowWay(clueFollowQO.getFollowWay());
                opportunityDynamic.setFollowDetail(clueFollowQO.getFollowDetail());
            }else{
                opportunityDynamic.setOpportunityStatus(clueFollowQO.getOpportunityStatus());
            }
            opportunityDynamic.setOperationMode(clueFollowQO.getOperationMode());
            opportunityDynamic.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            opportunityDynamic.setCreatePeopleId(userAccount.getAccountId());
            opportunityDynamic.setCreateTm(new Date());
            opportunityDynamic.setUpdatePeopleId(userAccount.getAccountId());
            opportunityDynamic.setUpdateTm(new Date());
            opportunityDynamic.setOpportunityId(clueFollowQO.getOpportunityId());
            result = opportunityDynamicDbService.addOpportunityDynamic(opportunityDynamic);

            Opportunity opportunity = opportunityDbService.selectByOpportunityId(clueFollowQO.getOpportunityId());
            //修改商机状态
            if(1 == clueFollowQO.getOperationMode()){
               opportunity.setOpportunityStatus(clueFollowQO.getOpportunityStatus());
               opportunity.setUpdatePeopleId(userAccount.getAccountId());
               opportunity.setUpdateTm(new Date());
                result = opportunityDbService.updateOpportunity(opportunity);
            }else{
                if(clueFollowQO.getEstimatedSigningTime() != null) {
                    opportunity.setEstimatedSigningTime(clueFollowQO.getEstimatedSigningTime());
                    opportunity.setOpportunityStatus(clueFollowQO.getOpportunityStatus());
                    opportunity.setUpdatePeopleId(userAccount.getAccountId());
                    opportunity.setUpdateTm(new Date());
                    result = opportunityDbService.updateOpportunity(opportunity);
                }
            }


        //}
        List<OpportunityDynamicVO> list = new ArrayList<>();
        if(result){
            list = opportunityDynamicDbService.opportunityDynamicList(clueFollowQO.getOpportunityId(),opportunityDynamicId);
        }
        return list;
    }

    public String insertClueVisitVecord(ClueFollowQO clueFollowQO, UserAccount userAccount) {
        ClueVisitRecord clueVisitRecord =  new ClueVisitRecord();
        clueVisitRecord.setClueVisitRecordId(UUID.randomUUID().toString().replaceAll("-", ""));
        if(clueFollowQO.getFollowWay()==2){
            clueVisitRecord.setType(1);//拜访
        }else{
            clueVisitRecord.setType(2);//陪访
        }

        clueVisitRecord.setVisitAddress(clueFollowQO.getVisitAddress());//===========拜访地址 类型为这个的时候 传这个参数
        clueVisitRecord.setAccompanyVisitPeople(clueFollowQO.getContactName());//拜访人or配方人
        clueVisitRecord.setContactPerson(clueFollowQO.getContactName());//联系人
        clueVisitRecord.setContactInformation(clueFollowQO.getContactInformation());//联系电话
        //沟通时长（秒）
        /*if (clueFollowQO.getFollowWay() == 1){
            clueVisitRecord.setCommunicationTime(clueFollowQO.getCommunicationTime());//沟通时长（秒） 页面秒
        } else {
            clueVisitRecord.setCommunicationTime(clueFollowQO.getCommunicationTime()*60);//沟通时长（秒） 页面分钟
        }*/
        clueVisitRecord.setVisitDetail(clueFollowQO.getFollowDetail());//详情
        clueVisitRecord.setUploadId(clueFollowQO.getAccountUploadId());//电话账号附件id
        clueVisitRecord.setMinUploadId(clueFollowQO.getMinUploadId());//电话时长附件id
        clueVisitRecord.setDeleteStatus(Short.parseShort("0"));
        clueVisitRecord.setCreatePeopleId(userAccount.getAccountId());//创建人
        //clueVisitRecord.setCreateTm(clueFollowQO.getFollowTm());//创建时间（跟进日期）
        clueVisitRecord.setCreateTm(new Date());
        clueVisitRecord.setUpdatePeopleId(userAccount.getAccountId());//更新人id
        clueVisitRecord.setUpdateTm(new Date());//更新时间
        //clueVisitRecord.setClueId(clueFollowQO.getClueId());//线索id
        if(!StringUtils.isBlank(clueFollowQO.getClueId())) {
            clueVisitRecord.setClueId(clueFollowQO.getClueId());//线索id
        }else{
            clueVisitRecord.setClueId("");//线索id
        }
        clueVisitRecord.setMainVisitor(clueFollowQO.getMainVisitor());//主拜访人
        clueVisitRecord.setAccompanyingPerson(clueFollowQO.getAccompanyingPerson());//陪访人
        clueVisitRecord.setCustomerId(clueFollowQO.getCustomerId());//客户id
        clueVisitRecord.setSingleProductCustomerId(clueFollowQO.getSingleProductCustomerId());//单品客户主键ID
        clueVisitRecord.setFollowSource(clueFollowQO.getFollowSource());//跟进来源
        if(clueVisitRecordDbService.insertClueVisitVecord(clueVisitRecord)>0){
            return clueVisitRecord.getClueVisitRecordId();
        }else{
            return "";
        }
    }


    /**
     * 商机-商机详情-查询当前商机动态
     * @param opportunityId 商机id
     * @return
     */
    @Override
    public DhPageInfo<OpportunityDynamicVO> opportunityDynamicList(Integer pageIndex, Integer pageSize, String sortName, String sortOrderString ,String opportunityId) {
        String opportunityDynamicId="";
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        List<OpportunityDynamicVO> list = opportunityDynamicDbService.opportunityDynamicList(opportunityId,opportunityDynamicId);

        PageInfo<OpportunityDynamicVO> pageInfo = new PageInfo<OpportunityDynamicVO>(list);
        return new DhPageInfo<OpportunityDynamicVO>(pageInfo, list);
    }
}
